package com.hanbang.gycatering.homepage;

import com.hanbang.gycatering.application.ActivityManager;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.UserInforData;
import com.hanbang.gycatering.comeon.LoginActivity;
import com.hanbang.gycatering.utils.BitmapUtil;
import com.hanbang.gycatering.utils.DbUtil;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MySharedPreferences;
import com.hanbang.gycatering.utils.MyToast;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.DbException;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class BaseFragmentActivity extends FragmentActivity {
	private String TAG = BaseActivity.class.getSimpleName();
	public BitmapUtils bitmapUtils = null;
	public UserInforData userData = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		userData = ((MyApplication) getApplication()).userData;
		bitmapUtils = BitmapUtil.getBitmapUtils(BaseFragmentActivity.this,
				MyApplication.bitmapCachePath);
		getDbUserData();
		ActivityManager.getInstance().pushActivity(this);
	}

	public void getDbUserData() {
		int id = MySharedPreferences.getSharedPreferencesKeyAndValue(this,
				MySharedPreferences.USER_DATA, "user_id", -1);
		if (id != -1) {
			try {
				userData = DbUtil.getDbUtils(this).findById(
						UserInforData.class, id);
			} catch (DbException e) {
				e.printStackTrace();
				userData = null;
			}
		} else {
			userData = null;
		}
	}

	public void setBackArrows(ImageView back) {
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		getDbUserData();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityManager.getInstance().exitActivity(this);
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		ActivityManager.getInstance().exitActivity(this);
	}

	public boolean isLogin(boolean isToLogin) {
		if (userData == null) {
			if (isToLogin) {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			}
			MyLog.e(TAG, "未登录");
			return false;
		} else {
			MyLog.e(TAG, "已登录");
			return true;
		}
	}

	public void passwordIsError(boolean isToast) {
		MySharedPreferences.setSharedPreferencesKeyAndValue(
				BaseFragmentActivity.this, MySharedPreferences.USER_DATA,
				"user_id", -1);
		userData = null;
		if (isToast) {
			MyToast.show(this, "用户名或密码错误,请重新登录!", Toast.LENGTH_SHORT);
		}
	}
}
